package com.lincoln.entity.user;

import com.lincoln.bean.SpringBeanFactoryUtils;
import com.lincoln.entity.permission.DbUserPermission;
import com.lincoln.service.UserPermissionService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class OauthUser implements UserDetails {
    public OauthUser() {

    }

    public OauthUser(DbUser user) {
        this.dbUser = user;
    }

    DbUser dbUser;

    /**
     * 获取用户所有的权限(包括role以及permission都会返回)
     *
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> authorities = new HashSet<>();
        authorities.add(new SimpleGrantedAuthority(dbUser.getRole().getName()));
        List<DbUserPermission> whites = ((UserPermissionService) SpringBeanFactoryUtils.getBeanByClass(UserPermissionService.class)).findUserWhitePermission(dbUser.getId());
        List<DbUserPermission> blacks = ((UserPermissionService) SpringBeanFactoryUtils.getBeanByClass(UserPermissionService.class)).findUserBlackPermission(dbUser.getId());
        dbUser.getRole().getPermissions().forEach(p -> {
            if(!blacks.contains(p)){
                authorities.add(new SimpleGrantedAuthority(p.getName()));
            }
        });
        for(DbUserPermission p:whites){
            authorities.add(new SimpleGrantedAuthority(p.getPermission().getName()));
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return dbUser.getPassword();
    }

    /**
     * 返回主键
     *
     * @return
     */
    @Override
    public String getUsername() {
        return dbUser.getId().toString();
    }

    @Override
    public boolean isAccountNonExpired() {
        return dbUser.isAccountNonExpired();
    }

    @Override
    public boolean isAccountNonLocked() {
        return dbUser.isAccountNonLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return dbUser.isCredentialsNonExpired();
    }

    @Override
    public boolean isEnabled() {
        return dbUser.isEnabled();
    }


}
